<template>
	<view class="container" style="padding-bottom: 100px" v-if="isLoaded">
		<!-- 表单 -->
		<view class="content" style="padding: 30rpx 30rpx 120rpx; background-color: #fff">
			<li-form>
				<!-- 基础信息 -->
				<li-form-item label="方案编码" required>
					<li-input :disabled="mode == 'edit'" v-model="form.programmeCode" rule="trim" prop="programmeCode" placeholder="请填写" v-on:blur="onBlurEvent($event)" />
				</li-form-item>
				<li-form-item label="方案名称" required>
					<li-input
						rule="trim"
						:disabled="mode == 'edit' && form.status != 0"
						v-model="form.programmeName"
						placeholder="请填写"
						v-on:blur="onBlurEvent($event)"
						prop="programmeName"
					/>
				</li-form-item>
				<li-form-item label="促销模式">
					<li-picker
						:disabled="mode == 'edit' && form.status != 0"
						prop="discountType"
						v-model="form.discountType"
						v-on:change="onPickerChange($event)"
						:rangeList="[
							{ id: 1, text: `特价` },
							{ id: 2, text: `折扣` }
						]"
					/>
				</li-form-item>
				<li-form-item label="促销人群">
					<li-picker
						:disabled="mode == 'edit' && form.status != 0"
						prop="discountUserType"
						v-model="form.discountUserType"
						:rangeList="[
							{ id: 0, text: `全部` },
							{ id: 1, text: `非会员` },
							{ id: 2, text: `会员` }
						]"
					/>
				</li-form-item>
				<li-form-item label="有效期范围">
					<uni-datetime-picker
						:disabled="mode == 'edit' && form.status != 0"
						prop="validityObject"
						v-model="form.validityObject"
						type="datetimerange"
						rangeSeparator="至"
					/>
				</li-form-item>
				<!-- <li-form-item label="星期选择">
          <li-checkbox :disabled="mode == 'edit' && form.status != 0" v-model="form.weekValueList" :rangeList="weekEnumable" prop="weekValueList"></li-checkbox>
        </li-form-item> -->
				<view class="l-form-item" label="星期选择" name="price">
					<view class="l-lbl required" style="width: 180rpx">星期选择:</view>
					<u-checkbox-group placement="column" v-model="form.weekValueList">
						<u-checkbox
							active-color="#f3c45d"
							:customStyle="{ marginBottom: '8px' }"
							v-for="(item, index) in weekEnumable"
							:key="index"
							:label="item.text"
							:name="item.id"
						></u-checkbox>
					</u-checkbox-group>
				</view>

				<li-form-item label="菜品范围">
					<li-picker
						prop="appointType"
						v-model="form.appointType"
						:disabled="form.discountType != 2 || (mode == 'edit' && form.status != 0)"
						:rangeList="[
							{ id: 0, text: `全部菜品` },
							{ id: 1, text: `指定菜品` },
							{ id: 2, text: `指定分类` }
						]"
					/>
				</li-form-item>
				<li-form-item label="全部菜品折扣" v-if="!form.appointType">
					<li-input
						rule="trim"
						:disabled="mode == 'edit' && form.status != 0"
						v-model="form.allDiscountValue"
						placeholder="请填写"
						v-on:blur="onBlurEvent($event)"
						prop="programmeName"
					/>
				</li-form-item>

				<li-form-item v-if="form.appointType != 0">
					<button v-if="form.status == 0" style="background-color: #f3c45d; margin-left: 80px" size="mini" type="primary" @click="onBtnClick(form.appointType)">
						选择{{ form.appointType == 1 ? '菜品' : '菜品分类' }}
					</button>
					<!-- foodList  -->
					<view class="spec-container" v-if="form.appointType == 1">
						<view class="spec-body">
							<block v-if="form.foodList.length > 0">
								<view class="items" style="border-bottom: 1px solid #cacaca; padding: 8px 0">
									<view class="is-default">商品名称</view>
									<view class="spec-name task-price">型号规格</view>
									<!-- <view class="price task-option" v-if="form.discountType === 2 ">原单价</view> -->
									<view class="price task-option">{{ form.discountType === 2 ? '促销折扣' : '特价' }}</view>
									<view class="price task-option">原单价</view>
									<view class="btns task-btn">操作</view>
								</view>
								<view v-for="(item, index) in form.foodList" :key="item.foodSpecId" class="items">
									<view class="is-default">
										<text>
											{{ item.foodName }}
										</text>
									</view>
									<view class="spec-name task-price">
										{{ item.specName }}
									</view>
									<view class="price task-option">
										<li-input
											v-if="form.discountType === 1"
											:disabled="mode == 'edit' && form.status != 0"
											:border="false"
											style="width: 50px; border-bottom: 1px solid #dadada"
											v-model="item.discountPrice"
											rule="float"
											v-on:blur="onBlur($event, item)"
										/>
										<li-input
											v-else
											:disabled="mode == 'edit' && form.status != 0"
											:border="false"
											style="width: 50px; border-bottom: 1px solid #dadada"
											v-model="item.discountValue"
											rule="int"
											v-on:blur="onBlur($event, item)"
										/>
									</view>
									<view class="price task-option">
										<text>
											{{ item.posPrice }}
										</text>
									</view>
									<view class="btns task-btn">
										<text
											class="btn btn-del"
											:style="{
												backgroundColor: mode == 'edit' && form.status != 0 ? '#fab6b6' : '#f56c6c'
											}"
											@click="btnDelItem(index, 1)"
											style="margin-left: 8px"
										>
											删除
										</text>
									</view>
								</view>
							</block>
							<block v-else>暂无菜品</block>
						</view>
					</view>
					<!--  foodCategoryList -->
					<view class="spec-container" v-else>
						<view class="spec-body">
							<block v-if="form.foodCategoryList.length > 0">
								<view>
									<view class="items" style="border-bottom: 1px solid #cacaca; padding: 8px 0">
										<view class="spec-name task-price">分类名称</view>
										<view class="spec-name task-price">促销折扣</view>
										<view class="btns task-btn">操作</view>
									</view>
								</view>
								<view v-for="(item, index) in form.foodCategoryList" :key="item.id" class="items">
									<view class="spec-name task-price">{{ item.foodName }}</view>
									<view class="spec-name task-price">
										<li-input
											:disabled="mode == 'edit' && form.status != 0"
											:border="false"
											style="width: 50px; border-bottom: 1px solid #dadada"
											v-model="item.discountValue"
											rule="int"
										/>
									</view>

									<view class="btns task-btn">
										<text
											:style="{
												backgroundColor: mode == 'edit' && form.status != 0 ? '#fab6b6' : '#f56c6c'
											}"
											class="btn btn-del"
											v-on:click="btnDelItem(index, 2)"
											style="margin-left: 8px"
										>
											删除
										</text>
									</view>
								</view>
							</block>
							<block v-else>暂无菜品分类</block>
						</view>
					</view>
				</li-form-item>

				<!-- <li-form-item label="促销门店">
          <li-radio
            :disabled="mode == 'edit' && form.status != 0"
            prop="isAllUseStore"
            v-model="form.isAllUseStore"
            :rangeList="[
              { id: 1, text: `全部门店` },
              {
                id: 0,
                text: `指定门店`
              }
            ]"
          /> 
        </li-form-item> -->
				<view class="l-form-item" label="促销门店" name="price">
					<view class="l-lbl required">促销门店:</view>
					<!-- <view class="l-form-right l-form-input"> -->
					<u-radio-group iconSize="14" v-model="form.isAllUseStore">
						<u-radio size="20" activeColor="#edac2f" :customStyle="{ marginTop: '12rpx' }" label="全部门店" :name="1"></u-radio>
						<u-radio size="20" activeColor="#edac2f" :customStyle="{ marginLeft: '8px', marginTop: '12rpx' }" label="指定门店" :name="0"></u-radio>
					</u-radio-group>
					<!-- </view> -->
				</view>

				<li-form-item prop="storeList" v-if="form.isAllUseStore != 1">
					<button type="primary" style="background-color: #f3c45d; margin-left: 80px" size="mini" v-if="form.status == 0" v-on:click="onBtnClick(3)">选择门店</button>

					<view class="spec-container">
						<view class="spec-body">
							<block v-if="form.storeList.length > 0">
								<view>
									<view class="items" style="border-bottom: 1px solid #cacaca; padding: 8px 0">
										<view class="spec-name task-price" style="justify-content: flex-start">门店名称</view>
										<view class="btns task-btn">操作</view>
									</view>
								</view>
								<view v-for="(item, index) in form.storeList" :key="item.id" class="items">
									<view class="spec-name task-price" style="justify-content: flex-start">
										{{ item.storeName }}
									</view>

									<view class="btns task-btn">
										<text
											class="btn btn-del"
											:style="{
												backgroundColor: mode == 'edit' && form.status != 0 ? '#fab6b6' : '#f56c6c'
											}"
											v-on:click="btnDelItem(index, 3)"
											style="margin-left: 8px"
										>
											删除
										</text>
									</view>
								</view>
							</block>
							<block v-else>暂无门店</block>
						</view>
					</view>
				</li-form-item>
			</li-form>
		</view>

		<!-- food Popup -->
		<next-tree
			ref="foodCategoryTreeSelector"
			:treeData="foodCategoryList"
			labelKey="name"
			valueKey="id"
			checkStrictly
			:selectParent="true"
			:funcMode="'checkbox'"
			@confirm="foodCategoryTreeConfirm"
		/>

		<!-- foodType Popup -->
		<u-popup :show="showAddFood" @close="closePopupAddFood" @open="openPopupAddFood" :closeable="true">
			<block>
				<view
					class="layout"
					style="height: 90vh; width: 100vw; background-color: #f7f8fa; font-size: 12px"
					:style="{
						display: type == 1 ? `flex` : `block`,
						paddingTop: type == 3 ? `50px` : `0`,
						paddingRight: type == 3 ? `12px` : `0`
					}"
				>
					<block v-if="type == 1">
						<view class="layout-left" style="height: 100%; width: 40vw; overflow-y: scroll">
							<view style="margin: 15rpx; background-color: #fff; border-radius: 10px; padding: 8px 4px" v-for="(item, index) in foodCategoryList" :key="item.id">
								<view class="fold" style="padding: 15rpx 15rpx 15rpx 0">
									<view class="tree-icon" style="margin: 0 5px" v-show="item.fold && item.children.length > 0" @click="unfold(index)">
										<!-- 向右箭头 -->
										<image style="width: 8px; height: 8px" src="/static/images/icon/down.png"></image>
									</view>
									<view @click="unfold(index)" style="margin: 0 5px" class="tree-icon" v-show="!item.fold && item.children.length > 0">
										<!-- 向下箭头 -->
										<image style="width: 8px; height: 8px" src="/static/images/icon/right.png"></image>
									</view>
									<view
										:style="{
											color: foodCategoryId == item.id ? '#f3c45d' : '#000',
											paddingLeft: item.children.length == 0 ? '20px' : '0px'
										}"
										@click="onItemClick(item)"
									>
										{{ item.name }}
									</view>
								</view>
								<block v-if="item.fold">
									<view v-for="(item1, index1) in item.children" class="subtree" :key="item1.id" style="display: flex; padding: 15rpx 15rpx 15rpx 0">
										<view
											class="tree-content"
											style="padding-left: 30px; padding-right: 20rpx"
											:style="{
												color: foodCategoryId == item1.id ? '#f3c45d' : '#000'
											}"
											@click="onItemClick(item1)"
										>
											<text>{{ item1.name }}</text>
										</view>
									</view>
								</block>
							</view>
						</view>
						<view class="layout-right" style="height: 100%; width: 60vw; overflow-y: scroll; padding-top: 40px">
							<block v-if="foodList != null && foodList.length > 0">
								<view class="food-items" style="font-size: 12px" v-for="(food, index) in foodList" :key="index">
									<image class="image" :src="food.image" style="align-self: center" />
									<view class="right" style="padding-bottom: 0">
										<text>名称：{{ food.name }}</text>
										<view class="mt-10">
											<text style="border: 1px solid #f7f8fa">规格：{{ food.foodSpecName }}</text>
										</view>
										<view class="mt-10">
											<text>价格：</text>
											<text class="text-red">￥{{ food.posPrice }}</text>
										</view>
									</view>
									<view class="btn" style="display: flex; align-items: center">
										<text
											@click="onPopItemClick(food, 1)"
											class="btn-yellow"
											style="border-radius: 8px; padding: 3px 5px; color: #fff"
											:style="{
												'background-color': form.foodList.some((itm) => itm.foodSpecId == food.foodSpecId) ? '#f56c6c' : '#f3c45d'
											}"
										>
											{{ form.foodList.some((itm) => itm.foodSpecId == food.foodSpecId) ? '取消' : '选择' }}
										</text>
									</view>
								</view>
							</block>
							<block v-else>
								<li-empty />
							</block>
						</view>
					</block>
					<block v-if="type == 3">
						<block v-if="StoreList != null && StoreList.length > 0">
							<view v-for="(item, index) in StoreList" :key="item.id" style="display: flex; align-items: center; margin-bottom: 10px">
								<view style="flex: 1; font-weight: 900; padding-left: 12px">
									{{ item.storeName }}
								</view>
								<button
									size="mini"
									@click="onPopItemClick(item, 3)"
									class="btn-yellow"
									style="border-radius: 8px; color: #fff"
									:style="{
										'background-color': form.storeList.some((itm) => itm.useStoreId == item.id) ? '#f56c6c' : '#24c322'
									}"
								>
									{{ form.storeList.some((itm) => itm.useStoreId == item.id) ? '取消' : '选择' }}
								</button>
							</view>
						</block>
						<li-empty v-else />
					</block>
				</view>
			</block>
		</u-popup>

		<li-bottom-btns
			:zIndex="10"
			v-if="mode == 'add' || (mode == 'edit' && form.status == 0)"
			:mode="mode"
			:showDel="false"
			v-on:btnDelClick="btnDelClick"
			v-on:btnEditOrSaveSubmitClick="btnEditOrSaveSubmitClick"
		/>
	</view>
</template>
<script>
import liFormMixin from '../../../mixins/liFormMixin';
import { GetDiscountRulesById, AddDiscountRules, DelDiscountRulesById, EditDiscountRules } from '../../../common/modules/catering.js';
import dateUtils from '../../../utils/date.js';
import { transferTypeEnum } from '../../../common/dataTransfer.js';
import { checkerType, modeEnum, booleanEnum, weekEnumable } from '../../../constants/normalConstants.js';
import { corpId, storeId } from '../../../constants/apiConstants.js';
import { GetFood, GetFoodCategoryList } from '../../../common/api.js';
import { GetCoreCmsStoreList } from '../../../common/modules/m.js';
import { validateTypeEnum } from '../../../utils/liValidator.js';
export default {
	mixins: [liFormMixin],
	async onLoad(options) {
		this.loadEvent(options, this);
	},

	async mounted() {
		this.mountedEvent(this, {
			corpId,
			storeId,
			status: 0,
			programmeCode: '',
			programmeName: '',
			discountUserType: 0,
			startTime: dateUtils.getTomorrow(),
			endTime: dateUtils.getTomorrow(),
			appointType: 1,
			discountType: 1,
			isAllUseStore: 0,
			weekValueList: [],
			storeList: [],
			foodList: [],
			foodCategoryList: [],
			validityObject: [dateUtils.getToday(), dateUtils.getTomorrow()],
			discountValue: 0.0
		});
	},
	data() {
		return {
			modeEnum,
			weekEnumable,
			booleanEnum,
			subject: '特价折扣商品',
			rootRoute: 'workbench',
			routeName: 'discountGoods',
			mode: 'add',
			isLoaded: false,
			id: null,
			allDiscountValue: 0,
			getFn: GetDiscountRulesById,
			addFn: AddDiscountRules,
			delFn: DelDiscountRulesById,
			editFn: EditDiscountRules,
			otherDataFns: [
				{
					fn: GetFoodCategoryList,
					name: 'foodCategoryList'
				}
			],
			/* form */
			form: null,
			/* popup */

			// transfer
			transferRules: [
				{
					name: 'programmeCode',
					type: transferTypeEnum.trim
				},
				{
					name: 'programmeName',
					type: transferTypeEnum.trim
				}
			],
			//check rule
			rules: {
				programmeCode: {
					type: validateTypeEnum.string,
					required: true,
					message: '请填写方案编码'
				},
				programmeName: {
					type: validateTypeEnum.string,
					required: true,
					message: '请填写方案名称'
				},
				allDiscountValue: [
					{
						asyncValidator: (_rule, value, callback) => {
							if (!this.form.appointType && !value) {
								return callback(new Error('请输入全部菜品菜品折扣'));
							}
							callback();
						}
					}
				],
				weekValueList: {
					asyncValidator: (_rule, value, _callback) =>
						new Promise((resolve, reject) => {
							if (value.length == 0) {
								reject('至少选择一天！');
							}
							resolve(true);
						})
				},
				storeList: {
					asyncValidator: (_rule, value, _callback) =>
						new Promise((resolve, reject) => {
							if (value.length == 0 && this.form.isAllUseStore == 0) {
								reject('至少选择一家门店！');
							}
							resolve(true);
						})
				},
				foodList: {
					asyncValidator: (_rule, value, _callback) =>
						new Promise((resolve, reject) => {
							if (value.length == 0 && this.form.appointType == 1) {
								reject('至少选择一种菜品！');
							}
							resolve(true);
						})
				},
				foodCategoryList: {
					asyncValidator: (_rule, value, _callback) =>
						new Promise((resolve, reject) => {
							if (this.form.discountType == 2 && value.length == 0 && this.form.appointType == 2) {
								reject('至少选择一种分类！');
							}
							resolve(true);
						})
				},
				validityObject: {
					type: validateTypeEnum.array,
					required: true,
					presence: true,
					message: '请选择时间范围',
					length: { exactly: 2 }
				}
			},

			lock: false,

			/* extra data */
			showAddFood: false,
			foodCategoryId: 0,
			foodList: [],
			foodCategoryList: [],
			type: 1,
			StoreList: []
			/* extra rules */

			/* extra transfer */
		};
	},

	methods: {
		onBlurEvent(e) {
			this.formBlur(e, this);
		},

		async getOtherData() {
			await this.batchGetData(this.otherDataFns);
			this.foodCategoryList.forEach((element) => {
				element.label = element.name;
				element.fold = true;
				element.active = false;
				if (element.children.length > 0) {
					element.children.map((item) => {
						item.label = item.name;
						item.fold = true;
					});
				}
			});

			if (this.foodCategoryList.length > 0) {
				this.foodCategoryList[0].active = true;
			}
			// ..
		},

		async btnEditOrSaveSubmitClick() {
			await this.formInsertOrEdit(this);
		},

		/* extra methods */
		btnDelItem: function (index, t) {
			if (this.mode == 'edit' && this.form.status != 0) {
				return;
			}
			this.form[t == 1 ? 'foodList' : t == 2 ? 'foodCategoryList' : 'storeList'].splice(index, 1);
		},

		onBtnClick: function (t) {
			this.type = t;
			t == 1 || t == 3 ? this.openPopupAddFood() : t == 2 ? (this.$refs.foodCategoryTreeSelector.showTree = true) : console.log('');
		},

		foodCategoryTreeConfirm: function (e) {
			delete e.id;
			this.form.foodCategoryList = e.map((item) => ({
				...e,
				foodOrCategoryId: item.id,
				discountPrice: 0.0,
				discountValue: 99.0,
				posPrice: 0.0,
				foodNumber: item.helpCode,
				foodName: item.name
			}));
		},

		openPopupAddFood: async function () {
			if (this.type == 1) {
				this.foodCategoryId = this.foodCategoryList[0].id;
				const res = await GetFood({
					pageNum: 1,
					pageSize: 9999,
					foodCategoryId: this.foodCategoryList[0].id
				});
				this.foodList = res.data.list.filter((item) => item.type == 1);
			}

			if (this.type == 3) {
				this.batchGetData([
					{
						name: 'StoreList',
						fn: GetCoreCmsStoreList
					}
				]);
			}

			this.showAddFood = true;
		},
		closePopupAddFood: async function () {
			this.showAddFood = false;
		},

		unfold(index) {},
		onItemClick: async function (item) {
			console.log(item, 'item');
			if (this.foodCategoryId == item.id) return;
			const res = await GetFood({
				pageNum: 1,
				pageSize: 9999,
				foodCategoryId: item.id
			});
			this.foodCategoryId = item.id;
			this.foodList = res.data.list.filter((item) => item.type == 1);
		},
		async onPopItemClick(item, t) {
			console.log(item, t);
			const res = this.form[t == 1 ? 'foodList' : 'storeList'].some((itm) => itm[t == 1 ? 'foodSpecId' : 'useStoreId'] == item[t == 1 ? 'foodSpecId' : 'id']);

			if (res) {
				const idx = this.form[t == 1 ? 'foodList' : 'storeList'].findIndex((itm) => itm[t == 1 ? 'foodSpecId' : 'useStoreId'] == item[t == 1 ? 'foodSpecId' : 'id']);
				this.form[t == 1 ? 'foodList' : 'storeList'].splice(idx, 1);
			} else {
				this.form[t == 1 ? 'foodList' : 'storeList'].push(
					t == 1
						? {
								...item,
								foodOrCategoryId: item.foodSpecId,
								discountPrice: 0,
								discountValue: 99.0,
								posPrice: item.posPrice,
								foodNumber: item.number,
								foodName: item.name,
								specName: item.foodSpecName,
								foodCode: ''
						  }
						: {
								...item,
								useStoreId: item.id,
								storeName: item.storeName
						  }
				);

				// this.form.foodList.forEach((item) => delete item.id);
			}
		},

		onPickerChange: function (e) {
			if (e.detail.value == 1) {
				this.form.appointType = 1;
			}
		},
		onBlur: function (e, item) {
			if (this.form.discountType === 2) {
				if (item.discountValue > 99) {
					item.discountValue = 99;
				}
				if (item.discountValue < 0) {
					item.discountValue = 0;
				}

				item.discountPrice = (item.discountValue * item.posPrice) / 100;
			}
		}
		// method put on the top
	}
};
</script>
<style lang="scss" scoped>
@import '~@/static/styles/commonStyle.scss';

.spec-container {
	background-color: #fff;
	border-radius: 10px;
	margin: 10px 0;
	padding: 8px 4px;

	.spec-header {
		padding: 10px;
		border-bottom: 1px solid #ededed;
		display: flex;
		justify-content: space-between;
	}

	.spec-body {
		padding: 15px 10px;

		.items {
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 12px;
			border-bottom: 1px solid #cacaca;
			padding: 8px 0;
			&:last-child {
				border-bottom: none;
			}

			.is-default {
				width: 80px;
				display: flex;
				justify-content: center;
				color: #000;
				background-color: #fff;
				.is-default-active {
					color: #fff;
					background-color: #fdc31d;
				}
			}

			.spec-name {
				flex: 1;
				display: flex;
				justify-content: center;
				&.task-price {
					width: 80px;
				}
			}

			.price {
				width: 80px;
				display: flex;
				justify-content: center;
				&.task-option {
					width: 60px;
				}
			}

			.btns {
				width: 90px;
				display: flex;
				justify-content: center;
				&.task-btn {
					width: 70px;
					font-size: 12px;
				}
			}

			.btn {
				border: 1px solid #ededed;
				padding: 12rpx 12rpx;
				border-radius: 5rpx;
				&.btn-del {
					background-color: #f56c6c;
					color: #fff;
				}
			}
		}
	}
}

.food-items {
	display: flex;
	padding: 5px;
	border: 1px solid #cacaca;
	border-radius: 8px;
	margin-bottom: 10px;
	margin-right: 10px;
	margin-left: 10px;
	.image {
		width: 160rpx;
		height: 100rpx;
		margin-right: 20rpx;
		border-radius: 8rpx;
		background-color: $bg-color-grey;
	}

	.right {
		flex: 1;
		// height: 160rpx;
		// overflow: hidden;
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		justify-content: space-between;
		border-bottom: 1px #f8f8f8 solid;
		padding-bottom: 20rpx;

		.label {
			display: flex;
			margin-top: 10rpx;

			text {
				display: inline-block;
				padding: 0 8rpx;
				font-size: 20rpx;
				border: 1px #f3c45d solid;
				border-radius: 8rpx;
				margin-right: 10rpx;
			}
		}

		.btn {
			display: flex;
			margin-top: 10rpx;

			text {
				display: inline-block;
				padding: 4rpx 16rpx;
				font-size: 24rpx;
				border: 1px #333 solid;
				border-radius: 8rpx;
				margin-right: 10rpx;
			}
		}
	}
}

.img {
	width: 20px;
	height: 20px;
}

.fold {
	display: flex;
}
</style>
